<?php

defined('SYSPATH') OR die('No direct access allowed.');

class Controller_Files extends Controller_Initialize {

  public $secure_actions = array(
      // user actions
      'upload' => 'login',
      'upload_img' => 'login',
  );

  /*
   * 
  public $auth;
  public $session;
  public $session_id;

  public function before() {
    parent::before();

    ($_SERVER['HTTP_USER_AGENT'] === 'Shockwave Flash' AND ($this->session_id = Security::xss_clean(arr::get($_POST, 'session', null))));
    $this->session = Session::instance(NULL, $this->session_id);
    $this->auth = Auth::instance();
  }
   *
   */

   public function action_uploadify() {

    $this->auto_render = FALSE;

    if (!empty($_POST) && !empty($_FILES)) {
      $files = Validate::factory($_FILES);
      $files->rules('Filedata', array('Upload::not_empty' => NULL, 'Upload::type' => array(array('jpg')), 'Upload::size' => array('800K')));

      if ($files->check()) {
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . '/temp/';
        $targetFile = str_replace('//', '/', $targetPath) . $_FILES['Filedata']['name'];

        move_uploaded_file($tempFile, $targetFile);
        echo 'ok';
      } else {
        // Error must begin with ERROR:
        echo "ERROR: Soubory nebyly nahrány.";
      }
    }
  }

  public function action_thumb($id) {

    $photo_source = ORM::factory('photo_source')->where('id', '=', $id)->find();

    $this->template->content = View::factory('templates/files/upload_thumb')
            ->bind('photo_source', $photo_source);

    if (!empty($_POST)) {
      $photo = Image::factory('files/users/'.$this->userAuth->username.'/' . $photo_source->filename);
      $photo->crop($_POST['w'], $_POST['h'], $_POST['x'], $_POST['y']);
      $photo->resize(210, 180);

      $photo_user = ORM::factory('photo_user', $photo_source->photo_user->find());
      $photo_user->thumb = 'thumb_' . $photo_user->date . '.jpg';

      if ($photo->save('files/users/'.$this->userAuth->username.'/thumb_' . $photo_user->date . '.jpg') && $photo_user->save()) {
        Message::add('success', '<strong>Náhled byl vytvořen.</strong>');
        Request::instance()->redirect('/');
      } else {
        Message::add('warning', '<strong>Náhled nebyl vytvořen.</strong>');
        Request::instance()->redirect('/');
      }
    }
  }

  public function action_upload() {

    $view = View::factory('templates/files/upload');

    if (!empty($_POST)) {
      $file_name = explode(",", $_POST['src']);

      $model = null;
      $model = ORM::factory('photo_user');
      $post = $model->validate_upload_inputs($_POST);

      if ($post->check()) {
        $upload_date = Time();

        // temporary photo thumb
        $thumb = Image::factory('temp/' . $file_name[0]);
        if ($thumb->width > $thumb->height) {
          $thumb->resize(NULL, 180);
        } else {
          $thumb->resize(210, NULL);
        }
        $thumb->crop(210, 180);
        $thumb->sharpen(10);
        $thumb->save('files/users/' . $this->userAuth->username . '/thumb_' . $upload_date . '.jpg');

        $photo_user = ORM::factory('photo_user');
        $photo_user->username = $this->userAuth->username;
        $photo_user->values($_POST);
        $photo_user->thumb = 'thumb_' . $upload_date . '.jpg';
        $photo_user->date = $upload_date;

        // save all the records to DB
        $photo_user->save();
        
        if ($photo_user->saved()) {

          if (!empty($_POST['tags'])) {

            foreach (array_unique($_POST['tags']) as $tag) {

              if (trim($tag) != '') {
                $photo_tag_exist = ORM::factory('photo_tag')->where('tag', '=', trim($tag))->find();

                if (!$photo_tag_exist->loaded()) {
                  $photo_tag = ORM::factory('photo_tag');
                  $photo_tag->tag = trim($tag);
                  $photo_tag->save();
                  $photo_user->add('photo_tag', $photo_tag);
                  $photo_tag->clear();
                } else {
                  if (!$photo_tag_exist->has('photo_user', $photo_user)) {
                  $photo_user->add('photo_tag', $photo_tag_exist);
                  $photo_tag_exist->clear();
                  }
                }
              }
            }
          }

          // file upload position
          $file_count = 1;

          foreach ($file_name as $file) {

            $photo = Image::factory('temp/' . $file);

            if (!is_dir(DOCROOT . '/files/users/' . $this->userAuth->username)) {
              mkdir(DOCROOT . '/files/users/' . $this->userAuth->username, 0755, true);
            }

            if ($photo->width > 680) {
              $photo->save(DOCROOT . '/files/users/' . $this->userAuth->username . '/o_' . $upload_date . '_' . $file_count . '.jpg');
              $photo->resize(680, NULL);
            }

            $photo->save(DOCROOT . '/files/users/' . $this->userAuth->username . '/' . $upload_date . '_' . $file_count . '.jpg');
            $photo->resize(220, NULL);
            $photo->sharpen(10);
            $photo->save(DOCROOT . '/files/users/' . $this->userAuth->username . '/m_' . $upload_date . '_' . $file_count . '.jpg');
            $photo_source = ORM::factory('photo_source');
            $photo_source->filename = $upload_date . '_' . $file_count . '.jpg';
            $photo_source->save();
            $photo_user->add('photo_source', $photo_source);
            $photo_source->clear();
            $file_count++;
          }

          $view = View::factory('templates/files/upload_finished')
                          ->bind('photo_user', $photo_user);

        } else {
          Message::add('warning', '<strong>Omlouváme se ale nastala chyba při ukládání do naší databáze.</strong>');
        }

      } else {

        $informations = null;
        foreach ($post->errors('validate') as $item) {
          $informations .= '<span>' . $item . '</span>';
        }

        $this->template->infoPanelTop->errors = $post->errors('validate');
        Message::add('warning', '<strong>Fotografie nebyly nahrány.</strong> ' . $informations);
        $view->set('dataPost', $_POST);
      }
    }

    $this->template->content = $view;

  }

  public function action_upload_img() {

    $this->template = new View("templates/default_mini");
    $this->template->styles = array();
    $this->template->scripts = array();

    // Define defaults
      $styles = array('media/js/ui/photovoice_ui.css' => 'screen', 'media/js/ui/themes/base/jquery.ui.all.css' => 'screen', 'media/css/default.css' => 'screen');
      $scripts = array('media/js/jquery-ui-selectmenu.js','media/js/jquery-ui-1.8.6.custom.min.js', 'media/js/photovoice.js', 'media/js/jquery.js', 'media/js/html5.js');

      // Add defaults to template variables.
      $this->template->styles = array_reverse(array_merge($this->template->styles, $styles));
      $this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));

    $view = View::factory('templates/files/upload_img');

    if (!empty($_POST)) {

      $file_name = explode(",", $_POST['src']);

      $upload_date = Time();
      $file_count = 1;

      foreach ($file_name as $file) {

        $photo = Image::factory('temp/' . $file);

        if (!is_dir(DOCROOT . '/files/users/' . $this->userAuth->username)) {
          mkdir(DOCROOT . '/files/users/' . $this->userAuth->username, 0755, true);
        }

        if ($photo->width > 440) {
          $photo->save(DOCROOT . '/files/users/' . $this->userAuth->username . '/o_' . $upload_date . '_' . $file_count . '.jpg');
          $photo->resize(440, NULL);
        }

        $photo->save(DOCROOT . '/files/users/' . $this->userAuth->username . '/' . $upload_date . '_' . $file_count . '.jpg');

        $model = ORM::factory('photo_file');
        $model->username = $this->userAuth->username;
        if ($file_count > 1) {
          $model->name = $_POST['name'] . ' ' . $file_count;
        } else {
          $model->name = $_POST['name'];
        }

        $model->filename = $upload_date . '_' . $file_count . '.jpg';
        $model->save();

        $file_count++;
      }

      Message::add('success', '<strong>Soubory byly nahrány.</strong>');

      Request::instance()->redirect($_SERVER['HTTP_REFERER']);
    }

    $this->template->content = $view;
  }

  public function action_upload_img_view() {

    $this->auto_render = false;
    $model = ORM::factory('photo_file')->where('username', '=', $this->userAuth->username)->find_all();
    $output = '';
    $output .= 'var tinyMCEImageList = new Array(';
    foreach ($model as $item) {
    $output .= '["'.$item->name.'", "/files/users/'.$this->userAuth->username.'/'.$item->filename.'"],';
    }
    $output = substr($output, 0, -1); // remove last comma from array item list
    $output .= ');';
    echo $output;

  }

  public function action_avatar($id) {
echo Kohana::debug($_FILES);
    if (!empty($_FILES)) {

      if (Auth::instance()->logged_in('admin')) {
        $model = ORM::factory('user', $id);
      } else {
        $model = ORM::factory('user', $id)->where('username', '=', $this->userAuth->username);
      }

      if ($_FILES['filedata']['size'] > 0 && $model->id) {
        $files = Validate::factory($_FILES)
        ->rules('filedata', array(
        'Upload::not_empty' => array(),
        'Upload::valid' => array(),
        'Upload::type' => array('Upload::type' => array('gif')),
        'Upload::size' => array('250K'))
        );

        if($files->check()) {
          $filename = upload::save($_FILES['filedata'],NULL, DOCROOT.'/temp');

          $image = Image::factory($filename);
          if ($image->width != 60 || $image->height != 50) {
            $image->resize(60, 50, Image::NONE);
          }
          $image->save(DOCROOT.'files/users/'.$model->username.'/'.$model->username.'.gif');

          unlink($filename);
        } else {
          $this->template->infoPanelTop->errors = $files->errors();
          Message::add('warning', '<strong>Avatar nesplňuje předepsané požadavky.</strong> ');
        }
      }
      
      Request::instance()->redirect('/'.$model->username);
    } else {
      Message::add('warning', '<strong>Ava.</strong> ');
      //Request::instance()->redirect('/');
    }
  }

   /**
   * Fill in default values for our properties before rendering the output.
   */
  public function after() {
    if ($this->auto_render) {

      $styles = array('media/js/uploadify/uploadify.css' => 'screen','media/js/jcrop/jquery.jcrop.css' => 'screen');

      $this->template->styles = array_reverse(array_merge($this->template->styles, $styles));

      $scripts = array('media/js/uploadify/jquery.uploadify.v2.1.4.min.js', 'media/js/uploadify/swfobject.js', 'media/js/jcrop/jquery.jcrop.min.js');

      $this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));
    }

    // Run anything that needs to run after this.
    parent::after();
  }

}